package com.promise.jokerdream.work.faction

import com.promise.jokerdream.database.entity.FactionCommerceGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 商会工作
class FactionCommerceWork(
    private val config: FactionCommerceGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "商会"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 领取商会礼包
            if (config.treasureBoxEnabled) {
                executeGiftClaim()
            }
            
            // 2. 商会交易
            val selectedTradingRewardsList = if (config.selectedTradingRewards.isEmpty()) emptyList() else config.selectedTradingRewards.split(",").map { it.trim() }
            if (config.tradingEnabled && selectedTradingRewardsList.isNotEmpty()) {
                executeTrading(selectedTradingRewardsList)
            }
            
            // 3. 商会兑换
            val selectedExchangeRewardsList = if (config.selectedExchangeRewards.isEmpty()) emptyList() else config.selectedExchangeRewards.split(",").map { it.trim() }
            if (config.exchangeEnabled && selectedExchangeRewardsList.isNotEmpty()) {
                executeExchange(selectedExchangeRewardsList)
            }
            
            WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 1. 领取商会礼包
     */
    private suspend fun executeGiftClaim(): WorkResult {
        val queryResult = gameApi.queryFactionCommerceGift()
        
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                // 循环领取礼包，直到没有可领取的礼包
                var currentResponse = response
                var hasGifts = currentResponse.giftInfo.isNotEmpty()

                while (hasGifts) {
                    // 领取第一个礼包
                    val firstGift = currentResponse.giftInfo.first()
                    val giftResult = gameApi.getFactionCommerceGift(firstGift.giftId, firstGift.type)

                    giftResult.foldWithApiException(
                        onSuccess = { giftResponse ->
                            val msg = giftResponse.getDescription()
                            historyManager.addHistory(name, giftResponse.getDescription())
                            if (msg != "获取帮派锁失败，系统错误") {
                                currentResponse = giftResponse
                                hasGifts = currentResponse.giftInfo.isNotEmpty()
                            } else {
                                historyManager.addHistory(name, "something was wrong")
                            }
                        },
                        onFailure = { code, msg ->
                            val innerCode = if (msg == "获取帮派锁失败，系统错误") 0 else code
                            historyManager.addHistory(name, msg, innerCode)
                            hasGifts = innerCode == 0 // 领取失败则停止循环
                        }
                    )
                }
                WorkResult.Success
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }
    
    /**
     * 2. 商会交易
     */
    private suspend fun executeTrading(selectedTradingRewards: List<String>): WorkResult {
        val queryResult = gameApi.queryFactionCommerceTrade()
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                // 筛选符合配置且未交易的商品并去重
                val matchedGoods = response.tradeInfo.filter { tradeModel ->
                    selectedTradingRewards.any { reward -> 
                        tradeModel.tips.contains(reward) 
                    } && tradeModel.isTraded == 0
                }.distinctBy { it.goodsId }
                
                // 逐个交易
                for (tradeModel in matchedGoods) {
                    val tradeResult = gameApi.factionCommerceTrade(tradeModel.goodsId, tradeModel.type)
                    tradeResult.foldWithApiException(
                        onSuccess = { tradeResponse ->
                            historyManager.addHistory(name, tradeResponse.getDescription())
                        },
                        onFailure = { code, msg ->
                            historyManager.addHistory(name, msg, code)
                        }
                    )
                }
                WorkResult.Success
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }
    
    /**
     * 3. 商会兑换
     */
    private suspend fun executeExchange(selectedExchangeRewards: List<String>): WorkResult {
        val queryResult = gameApi.queryFactionCommerceExchange()
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                var currentCoinNum = response.coinNum
                
                // 筛选符合配置的商品
                val matchedGoods = response.exchangeInfo.filter { exchangeModel ->
                    selectedExchangeRewards.any { reward -> 
                        exchangeModel.goodsName.contains(reward) 
                    }
                }
                
                // 逐个兑换，每次兑换前检查银币是否足够
                for (exchangeModel in matchedGoods) {
                    if (currentCoinNum >= exchangeModel.coinNum && exchangeModel.isExchanged != 1) {
                        val exchangeResult = gameApi.factionCommerceExchange(exchangeModel.typeId)
                        exchangeResult.foldWithApiException(
                            onSuccess = { exchangeResponse ->
                                historyManager.addHistory(name, exchangeResponse.getDescription())
                                // 兑换成功后减少银币
                                currentCoinNum -= exchangeModel.coinNum
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                }
                WorkResult.Success
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                WorkResult.Failure(Exception(msg), msg)
            }
        )
    }
}